package com.atguigu.gulimall.test.config;

import com.atguigu.gulimall.test.anotation.LuBan;
import lombok.SneakyThrows;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;

/**
 * Bean 的后置处理器，这个接口，可以修改 返回Bean的类型，
 */
public class MyBeanPostProcessor implements BeanPostProcessor {
    /**
     * 实例化之前
     * @param bean
     * @param beanName
     * @return
     * @throws BeansException
     */
    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        return null;
    }

    /**
     *  bean初始化方法调用后被调用
     * @param bean
     * @param beanName
     * @return
     * @throws BeansException
     */
    @SneakyThrows
    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        if("student".equalsIgnoreCase(beanName)){
            Class<?> aClass = bean.getClass();
            Field[] fields = aClass.getDeclaredFields();
            for (int i = 0; i < fields.length; i++) {
                LuBan annotation = fields[i].getAnnotation(LuBan.class);
                if(annotation!=null){
                    fields[i].setAccessible(true);
                    System.out.println("获取注解中的值："+annotation.name());
                    // 给当前这个Bean对象 中的 fields[i]字段 赋值 为刘君
                    fields[i].set(bean,annotation.name());
                }

            }
        }
        return bean;
    }
}
